<?php

declare (strict_types=1);
namespace App\Middleware;

use App\Constants\ErrorCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Exception\TokenValidException;
use App\Model\User;
class JTAuthMiddleware implements MiddlewareInterface
{
    use \Hyperf\Di\Aop\ProxyTrait;
    use \Hyperf\Di\Aop\PropertyHandlerTrait;
    function __construct()
    {
        $this->__handlePropertyHandler(__CLASS__);
    }
    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;
    /**
     * @Inject
     * @var HttpResponse
     */
    protected $response;
    /**
     * @Inject
     * @var JWT
     */
    protected $jwt;
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
    {
        $auth = $this->request->getHeader('Authorization')[0] ?? '';
        //游客模式不带token
        if (trim($auth) == 'Bearer' || trim($auth) == '') {
            return $handler->handle($request);
        }
        try {
            $tokenData = $this->jwt->getParserData();
            // log_info(__CLASS__ . "==tokenData==" . \json_encode($tokenData));
            if ($data = $this->jwt->checkToken()) {
                $userId = $tokenData['uid'];
                $user = User::find($userId);
                if (!$user) {
                    throw new TokenValidException('Token未验证通过', 401);
                    // return $handler->handle($request);
                }
                $request = $request->withAttribute('user', $user);
                $request = $request->withAttribute('userId', $userId);
                Context::set(ServerRequestInterface::class, $request);
            }
        } catch (\Exception $e) {
            // throw new TokenValidException('Token未验证通过-异常:' . $e->getMessage(), 401);
            // $request = $request->withAttribute('user', null);
            // $request = $request->withAttribute('userId', 0);
            // $response = Context::get(ResponseInterface::class);
            log_info(__CLASS__ . "==token验证异常==Message:" . $e->getMessage() . "==CheckToken:" . $data);
            // $newVersion = $this->request->input('version', '1.0') >= '1.1.9';
            return $this->response->json(['ret' => -1, 'result' => ErrorCode::LOGIN_TOKEN_EXP, 'res_info' => '用户验证失败，请稍后重试～']);
        }
        return $handler->handle($request);
    }
}